﻿/// ****************************************************************************
/// Author:	        Robin Zhu
/// Create Date:	2012-2-6
/// Purpose: 		生成连接字符串的用户控件定义文件
/// ****************************************************************************
/// Modify By		Date			Remark
/// ****************************************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using System.Data.Common;
using System.Data.OleDb;
using System.Data;
using System.Data.Odbc;
using System.Data.SqlClient;

namespace RB.Developer.Tools
{
    /// <summary>
    /// UserControlConnStr.xaml 的交互逻辑
    /// 生成连接字符串的用户控件
    /// </summary>
    public partial class UserControlConnStr : UserControl
    {
        public UserControlConnStr()
        {
            InitializeComponent();
        }

        private void cmbDatabaseType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            XmlElement selected = (XmlElement)cmbDatabaseType.SelectedItem;
            cmbProvider.ItemsSource = selected.SelectNodes("Providers/Provider");

            if (cmbProvider.Items.Count > 0)
            {
                cmbProvider.SelectedIndex = 0;
            }
        }

        private void cmbProvider_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            XmlElement selected = (XmlElement)cmbProvider.SelectedItem;
            if (selected != null)
            {
                cmbFormat.ItemsSource = selected.SelectNodes("Formats/Format");

                if (cmbFormat.Items.Count > 0)
                {
                    cmbFormat.SelectedIndex = 0;
                }
            }
            else
            {
                cmbFormat.ItemsSource = null;
            }
        }

        private void btnSelectPath_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();

            System.Windows.Forms.DialogResult result = dialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                txtPath.Text = dialog.SelectedPath;
            }
        }

        private void cmbFormat_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            XmlElement selected = (XmlElement)cmbFormat.SelectedItem;
            if (selected != null)
            {
                txtTemplate.Text = selected.SelectSingleNode("Template").InnerText;
            }
        }

        private void btnGenerate_Click(object sender, RoutedEventArgs e)
        {
            string connstr = txtTemplate.Text.Replace("@Path", txtPath.Text);
            connstr = connstr.Replace("@ServerName", txtServer.Text);
            connstr = connstr.Replace("@DatabaseName", txtPath.Text);
            connstr = connstr.Replace("@UserId", txtUserId.Text);
            connstr = connstr.Replace("@Password", txtPwd.Text);
            txtConnectionString.Text = connstr;
        }

        private void btnTestConnect_Click(object sender, RoutedEventArgs e)
        {
            DbConnection conn = null;
            try
            {
                conn = GetConnection();
                if (conn != null && conn.State == System.Data.ConnectionState.Open)
                {
                    MessageBox.Show("Success!");
                    var schema = conn.GetSchema("Tables");
                    foreach (DataRow row in schema.Rows)
                    {
                        lstTableName.Items.Add(row["TABLE_NAME"]);
                    }
                }
            }
            catch (DbException ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                    conn.Dispose();
                }
            }
        }


        private DbConnection GetConnection()
        {
            XmlElement selected = (XmlElement)cmbProvider.SelectedItem;
            if (selected != null)
            {
                var objectTypeNode = selected.SelectSingleNode("ObjectType");
                if (objectTypeNode != null)
                {
                    DbConnection conn = null;
                    if (objectTypeNode.InnerText == "SqlConnection")
                    {
                        conn = new SqlConnection();
                    }
                    else if (objectTypeNode.InnerText == "OleDbConnection")
                    {
                        conn = new OleDbConnection();
                    }
                    else if (objectTypeNode.InnerText == "OdbcConnection")
                    {
                        conn = new OdbcConnection();
                    }
                    if (conn != null)
                    {
                        conn.ConnectionString = txtConnectionString.Text;
                        conn.Open();

                        return conn;
                    }
                }
            }
            return null;
        }

        private void lstTableName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string tableName = (string)lstTableName.SelectedItem;
            if (tableName != null)
            {
                DbConnection conn = null;
                DbDataReader reader = null;
                try
                {
                    conn = GetConnection();
                    DbCommand cmd = conn.CreateCommand();

                    cmd.CommandText = "SELECT * FROM " + tableName;
                    reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly);
                    var schema = reader.GetSchemaTable();
                    dbgrdFields.ItemsSource = schema.DefaultView;
                }
                catch (DbException ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                        reader.Dispose();
                    }
                    if (conn != null)
                    {
                        conn.Close();
                        conn.Dispose();
                    }
                }
            }
        }
    }
}
